/*
 * PathConverter.java
 * 
 * last update: 14.01.2010 by Stefan Saru
 * 
 * author:	Felix(felix@ulise.cs.pub.ro)
 *
 * Obs: N/A
 */

package ide;


import java.io.*;


public class PathConverter {


	public PathConverter() {
	}


	public static void main(String args[]) {


		System.out.println(toRelativePath(args[0], args[1]) + "    (result)");

	}

	public static String toRelativePath(String basePath, String requestedPath) {
		//basePath must point to a  Directory.



		String resultPath = new String();

		//System.out.println(basePath + "(BasePath)");
		//System.out.println(requestedPath + "(RequestedPath)");

		try {
			basePath = new File(basePath).getCanonicalPath() + File.separatorChar;
			requestedPath = new File(requestedPath).getCanonicalPath() + File.separatorChar;
		} catch (Exception e){
			//System.out.println(e.toString());
			return null;
		}

		//System.out.println("    " + basePath + "     (BasePath absolutized)");
		//System.out.println("    " + requestedPath + "    (RequestedPath absolutized)");

		// now I'm sure that they're absolute.

		int index;

		// separatorChar appears at lest one time in an absolute path

		index = basePath.indexOf(File.separatorChar);
		//rindex = requestedPath.indexOf(File.separatorChar);

		if (!basePath.substring(0, index).equals(requestedPath.substring(0, index))) {
			//System.out.println("W95/98/NT/2000 : given paths are from different disks.");
			//System.out.println("This error never appears in OS'es with realy virtualized file system");
			return null;
		}

		int lastIndex;
		do {
			lastIndex = index;
			index = basePath.indexOf(File.separatorChar, index + 1);

			if ((index == -1) || (index > requestedPath.length())) break;
			//rindex = requestedPath.indexOf(File.separatorChar, rindex);

		} while (basePath.substring(0, index).equals(requestedPath.substring(0, index))); 

		//System.out.println(basePath.substring(0, lastIndex) + "   (Common part)");

		index = lastIndex;
		resultPath = resultPath + "." + File.separatorChar;

		while((index = basePath.indexOf(File.separatorChar, index + 1)) != -1)
			resultPath = resultPath + ".." + File.separatorChar;

		resultPath = resultPath + requestedPath.substring(lastIndex + 1, requestedPath.length() - 1);

		return resultPath;  
	}

	public static File toRelativePath(File basePath, File requestedPath) {
		try {
			return new File(toRelativePath(basePath.getCanonicalPath(), requestedPath.getCanonicalPath()));
		} catch (Exception e) {
			//System.out.println(e.toString());
			return null;
		}
	}
}
